package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.exception.ServiceException;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceParam;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.response.StatusCode;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    GeofenceMapper geofenceMapper;

    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQuery geofenceQuery) {
        log.debug("查询电子围栏信息业务,参数:{}", geofenceQuery);
        List<GeofenceVO> list = geofenceMapper.selectGeofence(geofenceQuery);
        return list;
    }

    @Override
    public void saveGeofence(GeofenceParam geofenceParam) {
        log.debug("修改电子围栏状态并保存,参数:{}", geofenceParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceParam, geofence);
        if (geofence.getId() != null) {//修改
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        } else {//新增
            geofence.setStatus("1");//每个围栏新增时都是启用状态
            geofence.setCreateTime(new Date());
            geofenceMapper.insert(geofence);
//        geofence.setId(geofenceParam.getId());
//        geofence.setStatus(geofenceParam.getStatus());
//        geofenceMapper.saveGeofence(geofenceParam);
        }
    }

    @Override
    public void deleteGeofence(Long id) {
        log.debug("删除电子围栏信息:{}",id);
        //业务:需要判断当前围栏上是否有已绑定的车辆 如果有绑定的车辆就不能删除
        //1.封装车辆查询的DTO层对象,VehicleQuery
        VehicleQuery vehicleQuery=new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        //2.调用车辆数据层查询是否有绑定在当前围栏上的车辆数据
        List<VehicleVO> list=vehicleMapper.selectVehicle(vehicleQuery);
        //3.如果当前围栏上有绑定车辆,业务层可以抛出操作失败的异常
        if (list.size()>0 && list!=null){
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else {
            geofenceMapper.deleteGeofence(id);
        }

    }
}
